﻿using System.Configuration;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using AutofacContrib.CommonServiceLocator;
using LogManager.Base;
using LogManager.Base.Data;
using LogManager.Config;
using LogManager.Config.Data;
using LogManager.LocalStorage.Data;
using Microsoft.Practices.ServiceLocation;
using Autofac.Integration.Mvc;

namespace LogManager
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            //Register data context
            RegisterContext(builder);

            var container = builder.Build();

            //Set resolver and controller factory
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //Create service Locator
            RegisterServiceLocator(container);

            //Add filters and routes
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        private static void RegisterServiceLocator(IContainer container)
        {
            var locator = new AutofacServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => locator);
        }

        private static void RegisterContext(ContainerBuilder builder)
        {
            builder.Register(c => ((LogConfigurationSection)ConfigurationManager.GetSection("logConfiguration")).LogCollection).As<LogCollection>().SingleInstance();
            builder.Register(c => ((ServerConfigurationSection)ConfigurationManager.GetSection("serverConfiguration")).ServerCollection).As<ServerCollection>().SingleInstance();  

            builder.RegisterType(typeof(ConfigServerService)).As<IServerService>().SingleInstance();
            builder.RegisterType(typeof(ConfigLogService)).As<ILogService>().SingleInstance();
            builder.RegisterType(typeof(LocalEventService)).As<IEventService>().SingleInstance();

            var configLogTypeService = new ConfigLogTypeService(((LogTypeConfigurationSection)ConfigurationManager.GetSection("logTypeConfiguration")).LogTypeCollection);
            var configEventTypeService = new ConfigEventTypeService(((EventTypeConfigurationSection)ConfigurationManager.GetSection("eventTypeConfiguration")).EventTypeCollection);
            
            //RegisterEventTypes(builder,configEventTypeService);
            RegisterLogTypes(builder,configLogTypeService);

            builder.Register(c => configLogTypeService).As<ILogTypeService>().SingleInstance();
            builder.Register(c => configEventTypeService).As<IEventTypeService>().SingleInstance();

            //builder.Register(c => new DefaultEventFactory()).As<IEventFactory>().SingleInstance();
            builder.Register(c => new LocatorLogFactory()).As<ILogFactory>().SingleInstance();
        }

        private static void RegisterLogTypes(ContainerBuilder builder, ILogTypeService service)
        {
            foreach (var logType in service.All())
            {
                builder.RegisterType(logType.Value).Named<ILog>(logType.Key).InstancePerDependency();
            }
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "DefaultEvent", // Route name
                "{controller}/{action}/{serverName}/{logName}/{id}", // URL with parameters
                new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                ); 

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}", // URL with parameters
                new { controller = "Dashboard", action = "Index"} // Parameter defaults
                );            
        }
    }
}